import api from '../../utils/api.js'
var app = getApp();
import {
    showLoading,
    hideLoading
} from "../../utils/util.js";
import {
    HTTP
} from "../../utils/http.js";
import { config } from '../../utils/config'
let http = new HTTP();
let sign = true; // 时间的标志

Page({
    data: {
        // 此页面 页面内容距最顶部的距离
        height: app.globalData.height * 2 + 20,
        list: [],
        num: 0,
        showModal: false, //收货方式model
        showModal1: false, //送达时间model
        status: 0, //快递配送 1， 到店自取 0
        deliveryDay: null, // 今天 0 ，明天 1
        data2: 0, // 选择的确定时间段
        show: false, // 是否展示 deliveryDay， data2
        time1: [], // 今天的时间段
        time2: [], // 明天的时间段
        today: {},
        beizhu: "",
        dizhi: "",
        address: "",
        shopAddress: null,
        showModel: false, //结算 按钮的模态窗口
        showModel: false, //结算 按钮的模态窗口
        yuding: {}, //商家是否支持预定优惠
        mark: true,
        yh: [], //商家原始设置的优惠
        filterYh: [], //过滤 所有最大力度的优惠
        totalMoneyInit: 0, //初始总价，没有计算任何优惠的
        totalMoney: 0,
        specialMoney: 0, // 以优惠多少钱
        imgUrl: config.imgUrl,
    },

    submit() {
        this.setData({
            showModal: true
        });
    },
    time() {
        var time = new Date();
        var data = time.getDate();
        var hours = time.getHours();
        var min = time.getMinutes();
        var today = {};
        today.data = data;
        today.hours = hours;
        today.min = min;
        this.setData({
            today,
            showModal1: true //弹出 选择送达时间的模态框
        });
        http.request({
            url: api.getTime,
            method: "POST",
            success: res => {
                var time = res.data;
                var time1 = [];
                var min = this.data.today.min;
                if (min < 10) {
                    min = "0" + min;
                }
                var today = this.data.today.hours.toString() + min;
                for (var i in time) {
                    var item1 = time[i].split("-")[0].split(":")[0];
                    var item2 = time[i].split("-")[0].split(":")[1];
                    var item = item1 + item2;
                    if (item - today > 0) {
                        time1.push(time[i]);
                    }
                }

                // //即今天的时间段为空时：
                // if (time1.length == 0) {
                //   this.setData({
                //     deliveryDay: 1
                //   });
                // }

                this.setData({
                    time2: res.data.data,
                    time1,
                    deliveryDay: 1 //默认明天
                });
            }
        });
    },
    beizhu(e) {
        this.setData({
            beizhu: e.detail.value
        });
    },
    xiugai() {
        var dizhi = wx.getStorageSync("address");
        dizhi = JSON.stringify(dizhi);
        wx.navigateTo({
            url: "/pages/changeDizhi/changeDizhi?dizhi=" + dizhi + "&status=1"
        });
    },
    wanshan() {
        wx.navigateTo({
            url: "/pages/wanshanDizhi/wanshanDizhi"
        });
    },
    toNum() {
        wx.navigateTo({
            url: "/pages/num/num?type=" + this.data.type
        });
    },
    xuanze1(e) {
        let timeNum = e.currentTarget.dataset.time; // 提取时间，是否是明天 是1 ，预定
        //当今天的时间段为空时，即只能预定了
        let time1 = this.data.time1;
        if (time1.length == 0) {
            return;
        } else {
            this.setData({
                deliveryDay: timeNum
            });
        }
        //若用户重选时间段，则覆盖
        wx.setStorageSync("timeField1", e.currentTarget.dataset.time);
    },
    xuanze2(e) {
        console.log('eeeeeeeeee', e)
        let filterYh = this.data.filterYh; // 过滤好的 优惠政策
        let totalMoneyInit = this.data.totalMoneyInit;
        let deliveryDay = e.currentTarget.dataset.day;

        this.setData({
            data2: e.currentTarget.dataset.time,
            showModal1: false,
            show: true,
            deliveryDay
        });
        this.getMoneyChange(filterYh, totalMoneyInit);
        //若用户重选时间段，则覆盖
        wx.setStorageSync("timeField2", e.currentTarget.dataset.time);
        if (!wx.getStorageSync("timeField1")) {
            wx.setStorageSync("timeField1", 0);
        }
    },
    changeA(e) {
        // 快递配送 status === 1 ,满包邮——discounts这个字段变成了true，不是number了
        console.log("快递配送", e);
        let status = e.currentTarget.dataset.status;
        let filterYh = this.data.filterYh; //优惠政策
        let totalMoneyInit = this.data.totalMoneyInit;

        this.setData({
            status,
            showModal: false
        });
        this.getMoneyChange(filterYh, totalMoneyInit);
    },
    changeB(e) {
        // 自行提取 status  === 0
        console.log("自提方式", e);
        let status = e.currentTarget.dataset.status;
        let filterYh = this.data.filterYh; // 过滤好的 优惠政策
        let totalMoneyInit = this.data.totalMoneyInit;

        this.setData({
            status,
            showModal: false
        });
        this.getMoneyChange(filterYh, totalMoneyInit);
    },
    close: function() {
        this.setData({
            showModal: false,
            showModal1: false
        });
    },
    //提交订单时，送达时间的缓存
    timeFieldStorage() {
        let timeField1 = wx.getStorageSync("timeField1"); // 0 今天  1明天
        let timeField2 = wx.getStorageSync("timeField2"); // 时间段
        console.log("timeField1", timeField1);
        if (timeField1 && timeField2) {
            this.setData({
                deliveryDay: timeField1,
                data2: timeField2,
                showModal1: false,
                show: true
            });
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        //正常的 从单品菜篮 ——进入
        let shopId = options.shopId;
        let shopAddress = options.shopAddress;
        if (shopId && shopAddress) {
            this.setData({
                shopAddress,
                shopId
            });
        }
        //获取地址
        http.request({
            url: api.oneAddress,
            method: "POST",
            data: {
                user_id: wx.getStorageSync("user_id")
            },
            success: res => {
                this.setData({
                    dizhi: res.data
                });
            }
        });
        //展示已选商品,总价，数量
        this.showProduct();

        //正常购买，循环支付未购买的菜单时,以及
        if (options.singleType == 1) {
            let singleShopList = wx.getStorageSync("singleShopList");
            if (singleShopList) {
                this.setData({
                    singleShopList
                });
                //ele.pon.type 优惠类型 1满减价格，2满送商品，3满免配送费，4预定优惠，5自提优惠
                let yh = singleShopList.yh;
                if (yh.length == 0) {
                    console.log("商家没有设置优惠！！！");
                    this.initTotalMoney(options);
                    return false;
                } else {
                    //状态 0正常  1 关闭此优惠条件
                    yh = yh.filter(ele => {
                        return ele.status == 0;
                    });
                    // //判断 商家 是否支持预定优惠
                    // let yuding = {
                    //   booking: false,
                    //   num: 0,
                    //   condition: 0
                    // };
                    // yh.forEach(ele => {
                    //   if (ele.pon.type == 4) {
                    //     yuding.booking = true;
                    //     yuding.num = Number(ele.discounts);
                    //     yuding.condition = ele.condition;
                    //   }
                    // });
                    this.setData({
                        yh,
                    });
                    this.initTotalMoney(options);
                }
            }
        } else if (options.againType == 0) {
            //从 再来一单 按钮 进入提交订单页面
            console.log("单品 再来一单");
            this.setData({
                againType: true
            });
            this.showContentAgain();
        }
    },
    //商品初始总价
    initTotalMoney(options) {
        let singleShopList = wx.getStorageSync("singleShopList");
        console.log("sssssssssss", options);
        let shipping_fee = Number(singleShopList.shipping_fee);
        let totalMoneyInit = Number(options.totalMoney); // 初始价格

        //判断商家是否开启配送is_delivery：0关闭 1开启
        //默认，自取，不计算配送费
        // 计算符合商家优惠条件后的总价
        let yh = singleShopList.yh;
        this.getTotalPrice(totalMoneyInit, yh);

        this.setData({
            totalMoneyInit,
            shopId: options.shopId
        });

        //需要多次循环支付时，使用送达时间的缓存
        // this.timeFieldStorage();
        // let deliveryDay = this.data.deliveryDay; // 等于 1 是明天配送
        // if (deliveryDay == 1) {
        //   // 提取时间，是否是明天 是1 ，预定
        //   let filterYh = this.data.filterYh; //优惠政策
        //   let totalMoney = this.data.totalMoney;
        //   let alreadyMoney = this.data.alreadyMoney;
        //   let totalMoneyInit = this.data.totalMoneyInit;
        //   if (filterYh) {
        //     filterYh.forEach((ele, index) => {
        //       if (ele.pon.type == 4 && totalMoneyInit > ele.condition) {
        //         //4 预定优惠
        //         totalMoney = totalMoney - Number(ele.discounts);
        //         alreadyMoney += Number(ele.discounts);
        //         ele.mark = true;
        //       }
        //     });
        //   }
        //   this.setData({
        //     totalMoney,
        //     alreadyMoney,
        //     filterYh
        //   });
        // }
    },
    // 计算满足优惠条件的总价，与不满足时
    getTotalPrice(initMoney, yh) {
        let filterYh = []; //展示所有符合最高力度的优惠条件
        let notYh = []; //展示未满足 - 更多优惠
        let status = this.data.status;
        let singleShopList = this.data.singleShopList;

        if (yh) {
            console.log('优惠计算', yh)
                //要满足 店铺开启配送， 设置了 配送费
            if (singleShopList.is_delivery === 1) {
                yh.forEach((ele) => {
                    if (ele.pon.type == 3) {
                        if (initMoney >= ele.condition) {
                            filterYh.push(ele)
                            ele.freeFee = true // 新建一个,满足，没有配送费
                            ele.shipping_fee = 0
                        } else {
                            filterYh.push(ele)
                            ele.freeFee = false
                            ele.shipping_fee = singleShopList.shipping_fee
                        }
                    }
                })
            }



            let arr1 = [];
            //取最大的满减
            yh.forEach((ele, index) => {
                if (ele.pon.type == 1) {
                    //满减,拿到 符合满减的条件
                    if (initMoney >= ele.condition) {
                        ele.myIndex = index;
                        arr1.push(ele);
                    } else {
                        notYh.push(ele);

                    }
                }
            });
            //拿到最大的满减力度,其在当前yh下的索引
            let maxFullMinus = this.getmaxCondition(arr1);
            console.log("拿到最大的满减力度", maxFullMinus);
            if (maxFullMinus != null || maxFullMinus != undefined) {
                filterYh.push(maxFullMinus);
            }

            let arr2 = [];
            //展示其最大的满送力度
            yh.forEach((ele, index) => {
                if (ele.pon.type == 2) {
                    // 满送食材
                    if (initMoney >= ele.condition) {
                        ele.myIndex = index;
                        ele.mark = true;
                        arr2.push(ele);
                    } else {
                        notYh.push(ele);
                    }
                }
            });
            //拿到最大的满送力度,其在当前yh下的索引
            let maxFullSend = this.getmaxCondition(arr2);
            console.log("拿到最大的满送力度", maxFullSend);
            if (maxFullSend != null || maxFullSend != undefined) {
                filterYh.push(maxFullSend);
            }

            let arr4 = [];
            //展示其最大的预定优惠力度
            yh.forEach((ele, index) => {
                if (ele.pon.type == 4) {
                    if (initMoney >= ele.condition) {
                        ele.myIndex = index;
                        arr4.push(ele);
                    } else {
                        notYh.push(ele);
                    }
                }
            });
            let maxFullBook = this.getmaxCondition(arr4);
            console.log("拿到最大的预定优惠力度", maxFullBook);
            if (maxFullBook != null || maxFullBook != undefined) {
                filterYh.push(maxFullBook);
            }

            let arr5 = [];
            //展示其最大的自提优惠力度
            yh.forEach((ele, index) => {
                if (ele.pon.type == 5) {
                    if (initMoney >= ele.condition) {
                        ele.myIndex = index;
                        arr5.push(ele);
                    } else {
                        notYh.push(ele);
                    }
                }
            });
            let maxFullPickUp = this.getmaxCondition(arr5);
            console.log("拿到最大的自提优惠力度", maxFullPickUp);
            if (maxFullPickUp != null || maxFullPickUp != undefined) {
                filterYh.push(maxFullPickUp);
            }
            this.getMoneyChange(filterYh, initMoney);
            this.setData({
                yh,
                notYh,
                filterYh
            });
        }
    },
    //返回符合条件的最大值
    getmaxCondition(arr) {
        // let ret = []
        // arrayobj.forEach( (ele,index) => {
        //   ret.push(Number(ele.condition))
        // })
        // let maxi = 0;
        // let max = Math.max.apply(null, ret);

        let maxVal = arr[0];
        for (let i of arr) {
            maxVal = Number(maxVal.condition) > Number(i.condition) ? maxVal : i;
        }
        return maxVal
    },
    //变更取货方式以及 取货时间时的价格变化
    //ele.pon.type 优惠类型 1满减价格，2满送商品，3满免配送费，4预定优惠，5自提优惠
    getMoneyChange(filterYh, totalMoneyInit) {
        let specialMoney = 0;
        let moneyIng = totalMoneyInit;
        let status = this.data.status;
        let deliveryDay = this.data.deliveryDay;
        console.log('moneyIng', moneyIng)
        filterYh.forEach((ele) => {
            if (ele.pon.type === 1) {
                moneyIng = moneyIng - Number(ele.discounts);
                specialMoney += Number(ele.discounts);
            } else if (ele.pon.type === 2) {
                //满送商品
            } else if (ele.pon.type === 3 && status == 1) {
                //满免配送费,不计入 优惠价格内
                if (ele.freeFee == false) {
                    moneyIng = moneyIng + Number(ele.shipping_fee);
                }
            } else if (ele.pon.type === 4 && deliveryDay == 1) { // 预定明天的优惠
                moneyIng = moneyIng - Number(ele.discounts);
                specialMoney += Number(ele.discounts);
            } else if (ele.pon.type === 5 && status == 0) { // status：0 自提优惠，1 配送
                moneyIng = moneyIng - Number(ele.discounts);
                specialMoney += Number(ele.discounts);
            }
        })


        this.setData({
            specialMoney,
            totalMoney: moneyIng
        })
    },


    // 从 再来一单 进入 页面，展示内容——单品
    showContentAgain() {
        let totalMoneyInit = 0;
        let againOrderItem = wx.getStorageSync("againOrderItem");
        let shopId = againOrderItem.shop_id; //店铺id
        let ids = []; // 单品 id
        let snap_items = againOrderItem.snap_items; //单品 是 数组
        console.log("snap_items", snap_items);

        this.setData({
            shopId,
            yh: againOrderItem.yh,
            shopAddress: againOrderItem.address || againOrderItem.shops.address
        });

        //验证 初始价格
        snap_items.forEach(ele => {
            ids.push(ele.product_id);
        });
        let idsString = ids.join();
        console.log("ids", idsString);

        this.tryAgainVerifyPrice(shopId, idsString).then(remoteData => {
            // 先取差集 ，在验证价格是否相等
            let ret = [];
            snap_items.forEach((ele, index) => {
                remoteData.forEach((rEle, rIndex) => {
                    if (rEle.product_id === ele.product_id) {
                        ele.price = Number(rEle.price);
                        ret.push(ele);
                    }
                });
            });
            //验证过后 重新计算初始价格,ret为当前可售卖的单品，未考虑ret为[]时；
            console.log("rrrrrr", ret);
            ret.forEach(ele => {
                totalMoneyInit += ele.price;
            });

            this.getTotalPrice(totalMoneyInit, againOrderItem.yh); //优惠后的 总价

            this.setData({
                recommendSelectedItem: ret,
                totalMoneyInit, // 验证过价格后，所有单品食材的总价，不变的
            });
        });
    },
    // 再来一单商品验证库存价格, 后端做了验证库存的判断
    //若单品 没有，则不会返回
    tryAgainVerifyPrice(shopId, ids) {
        let that = this;
        return new Promise(function(resolve, reject) {
            http.request({
                url: api.tryAgain,
                method: "POST",
                data: {
                    id: shopId,
                    ids: ids
                },
                success: res => {
                    console.log("res", res);
                    if (res.code == 200) {
                        let data = res.data;
                        let existID = []; //验证通过的产品id
                        data.forEach(ele => {
                            existID.push(ele.product_id);
                        });
                        that.setData({
                            existID
                        });
                        resolve(data);
                    } else {
                        console.log("验证不通过");
                    }
                },
                fail: err => {
                    console.log(err);
                }
            });
        });
    },

    //展示已选商品
    showProduct() {
        let totalMoney = 0;
        let num = 0;
        let vegetaleCurrent = wx.getStorageSync("vegetaleCurrent");
        if (!vegetaleCurrent) {
            return false;
        }
        vegetaleCurrent = vegetaleCurrent.filter((ele, index) => {
            return ele.mark == true;
        });
        vegetaleCurrent.map(item => {
            num += item.number;
        });
        vegetaleCurrent.map(item => {
            if (item.mark) {
                totalMoney += item.number * item.price;
            }
        });

        //测试以 分 为 单位
        this.setData({
            list: vegetaleCurrent,
            num,
            totalMoney: totalMoney.toFixed(2)
        });
    },
    // // 下单时，符合的促销优惠
    coupon_json() {
        let coupon_json = [];
        let filterYh = this.data.filterYh;
        if (filterYh) {
            //商家如有设置优惠政策时
            //循环符合优惠的 标签
            filterYh.forEach((ele, index) => {
                let ret = {};
                ret.condition = ele.condition;
                ret.discounts = ele.discounts;
                ret.name = ele.pon.name;
                ret.type = ele.pon.type;
                // 总价满足 商家设置的满足条件时，才加上
                if (ele.pon.type == 3) {
                    ret.shipping_fee = ele.shipping_fee
                }
                if (ele.pon.type == 2) {
                    ret.product_name = ele.product_name;

                }
                coupon_json[index] = ret;

            });
            // 过滤
            coupon_json = coupon_json.filter(ele => {
                if (ele != undefined || ele != null) {
                    return true;
                }
            });
        }

        // let status = this.data.status;
        //若果店铺没有设置 满多免配送费，type=3,且设置了 配送费，就要把配送费传过去
        let singleShopList = this.data.singleShopList;
        let shop_fee = singleShopList.shipping_fee
        coupon_json.push({
            type: 6,
            name: "配送费",
            fee: shop_fee
        })
        return coupon_json;
    },
    // 单品 ————下单支付
    zhifu() {
        var num = 0;
        let that = this;
        let list = this.data.list; // snap_items
        let snap_items = []; //订单详情信息
        var v = {}; //商品ID及其数量
        let user_id = wx.getStorageSync("user_id");

        // 构造订单 数据结构
        list.forEach((ele, index) => {
            snap_items[index] = {
                product_id: ele.product_id,
                product_name: ele.name || ele.product_name,
                price: ele.price,
                num: ele.num,
                unit: ele.unit,
                unitZn: ele.unitZn,
                main_img_url: ele.main_img_url
            };
            v[index] = {
                product_id: ele.product_id,
                num: ele.number
            }
        });
        console.log("vvvvvvvvvvvv", v);
        console.log("snap_items", snap_items);

        if (!this.data.detail) {
            console.log("没有地址");
            wx.showToast({
                title: "请填详细地址",
                icon: "none",
                duration: 1500,
                mask: true
            });
            return false;
        }
        if (this.data.status == 0) {
            if (this.data.data2 == 0) {
                wx.showToast({
                    title: "请填写自提时间",
                    icon: "none",
                    duration: 1500,
                    mask: true
                });
            } else {
                num++;
            }
        } else {
            if (this.data.data2 == 0) {
                wx.showToast({
                    title: "请填写送达时间",
                    icon: "none",
                    duration: 1500,
                    mask: true
                });
            } else {
                num++;
            }
        }

        var time = this.data.time2;
        var get_time_id = 0;
        for (var i in time) {
            if (time[i] == this.data.data2) {
                get_time_id = i * 1;
            }
        }

        let coupon_json = this.coupon_json();
        console.log("下单时 符合的优惠！！！！！", coupon_json);
        let parmsData = {
            user_id: user_id,
            total_price: this.data.totalMoney,
            snap_address: this.data.address + this.data.detail,
            total_count: this.data.num,
            get_time_id: get_time_id,
            remark: this.data.beizhu,
            receiving_method: this.data.status,
            send_day: this.data.deliveryDay,
            shop_id: this.data.shopId,
            snap_items: JSON.stringify(snap_items),
            v: JSON.stringify(v),
            mobile: this.data.dizhi.mobile,
            username: this.data.name,
            coupon_json: JSON.stringify(coupon_json) || [],
            type: 0
        };
        if (num == 1) {
            this.setData({
                showModel: true
            });
            http.request({
                url: api.placeOrder,
                method: "POST",
                header: {
                    "content-type": "application/x-www-form-urlencoded"
                },
                data: parmsData,
                success: res => {
                    console.log("创建订单成功", res);
                    let order_id = res.data.order_id;
                    if (res.code == 200) {
                        console.log("order_id", order_id);
                        that.pay(order_id, user_id);
                    } else {
                        wx.showToast({
                                title: '验证错误',
                                icon: 'none',
                                duration: 1500,
                            })
                            // setTimeout( ()=> {
                            //   wx.redirectTo({
                            //     url: '/pages/my/my'
                            //   })
                            // })
                    }
                }
            });
        }
    },
    pay(order_id, user_id, againType) {
        let that = this;
        wx.login({
            success: res => {
                http.request({
                    url: api.gotoPreOrder,
                    method: "POST",
                    data: {
                        uid: user_id,
                        oid: order_id
                    },

                    success: function(res) {
                        //后端返回的数据
                        console.log("res支付", res);
                        var data = res.data;
                        that.doWxPay(data, againType);
                    }
                });
            }
        });
    },
    doWxPay(param, againType) {
        //小程序发起微信支付
        wx.requestPayment({
            timeStamp: param.data.timeStamp, //timeStamp是字符串类型的，秒
            nonceStr: param.data.nonceStr,
            package: param.data.package,
            signType: "md5",
            paySign: param.data.paySign,
            success: function(event) {
                wx.redirectTo({
                    url: `/pages/paySuccess/paySuccess?againType=${againType}`,
                    success: function() {
                        console.log("支付完成跳转！！！", event);
                    }
                });
            },
            fail: function(error) {
                wx.showToast({
                    title: "支付取消",
                    icon: "none",
                    duration: 1500,
                    mask: true,
                    success: function() {
                        console.log("支付取消跳转！！！", error);
                        setTimeout(function() {
                            wx.reLaunch({
                                url: "/pages/myAllOrderList/myAllOrderList"
                            });
                        }, 2000);
                    }
                });
            },
            complete: function() {
                // complete
            }
        });
    },

    onShow: function(options) {
        this.setData({
            showModel: false
        });

        var address = wx.getStorageSync("address") || [];
        if (address.length == 0) {
            var that = this;
            let qqmapsdk = new QQMapWX({
                key: "OI5BZ-G3FWJ-A6VFG-FGA5U-AZHAT-2NBVY"
            });
            wx.getLocation({
                type: "wgs84",
                success(res) {
                    const latitude = res.latitude;
                    const longitude = res.longitude;
                    const speed = res.speed;
                    const accuracy = res.accuracy;
                    qqmapsdk.reverseGeocoder({
                        location: {
                            latitude,
                            longitude
                        },
                        success(res) {
                            console.log(res);
                            that.setData({
                                address: res.result.address_component.street
                            });
                        }
                    });
                }
            });
        } else {
            var detail = address.detail || "";
            if (detail) {
                this.setData({
                    address: address.address,
                    detail,
                    name: address.name,
                    phone: address.phone
                });
            } else {
                this.setData({
                    address: address.address,
                    detail: false
                });
            }
        }
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        wx.removeStorageSync("singleShopList");
    }
});